<?php
namespace Admin\Controller;

class MemberCouponController extends CommonController
{

    /**
     * 列表
     *
     * @param  void
     * @return void
     */
    public function index()
    {
        if (IS_POST) {
            $this->delete();
        } else {
            $keyword = I('get.keyword');
            $couponID = I('get.coupon_id', 0);
            $where = array();
            if ($keyword) {
                $where['m.nickname'] = array( 'like', "%{$keyword}%" );
            }
            if ($couponID){
                $where['c.coupon_id'] = $couponID;
            }
            
            $where['m.status'] = array( 'gt' , 0 );
            $model = M()->table('__MEMBER_COUPON__ AS c')->join('LEFT JOIN __MEMBER__ AS m ON c.member_id = m.member_id');
            $field = 'c.id,m.nickname,c.coupon_id,c.coupon_sn,c.status,c.coupon_name,c.coupon_value,c.start_time,c.end_time,c.send_type';
            $list = $this->lists($model, $field, $where, 'c.id DESC', 10);
            $coupon = getCouponList(false);
            $this->assign('coupon', $coupon);
            $this->assign('list', $list);
            $this->assign('keyword', $keyword);
            $this->assign('coupon_id', $couponID);
            $this->display();
        }
    }

    public function sendCoupon()
    {
        set_time_limit(0);
        if (IS_POST) {
            $memberIds = I('post.member_id');
            $couponID = I('post.coupon_id');
            if (empty($memberIds) || empty($couponID) ){
                $this->error('参数错误');
            }
            $memberIds = str_replace(['.', '，', '。', ' ', '|'], ',', $memberIds);
            $arr = explode(',', $memberIds);
            if ($arr) {
                foreach ($arr as $key => $value){

                    addMemberCoupon($value, $couponID);
                }
            }
            $this->success('发送成功', U('index'));
        } else {
            $coupon = getCouponList(false);
            $this->assign('coupon', $coupon);
            $this->display('sendCoupon');
        }
    }


    /**
     * 删除
     *
     * @param void
     * @return void
     */
    public function delete()
    {
        $id = array_unique((array) I('id', 0));
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        $where = array( 'id' => array( 'in', $id ) );
        $data = array( 'status' => 0, 'update_time' => time() );
        $result = M('MemberCoupon')->where($where)->save($data);
        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }  
    
}